package love.unknown.fruit.dao.base;

import java.sql.*;

public abstract class BaseDAO {
    public final String DRIVER = "com.mysql.jdbc.Driver";
    public final String URL = "jdbc:mysql://192.168.108.129:3306/fruitdb?characterEncoding=utf-8";
    public final String USER = "root";
    public final String PWD = "123456";

    protected Connection conn;
    protected ResultSet rs ;
    protected PreparedStatement ps;

    protected Connection getConn() {
        //1.加载驱动
        try {
            Class.forName(DRIVER);
            //2.通过驱动管理器获取连接对象
            return DriverManager.getConnection(URL, USER, PWD);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    protected void close(ResultSet rs, PreparedStatement ps, Connection conn) {
        try {
            if (rs != null)
                rs.close();
            if (ps != null)
                ps.close();
            if (conn != null && !conn.isClosed())
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //执行更新,返回影响行数
    protected int executeUpdate(String sql,Object ...params) {
        try {
            conn = getConn();
            ps = conn.prepareStatement(sql);
            if (params!=null&&params.length>0){
                int i = 1;
                for (Object o:
                     params) {
                    ps.setObject(i,params[i-1]);
                    i++;
                }
            }
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(rs,ps,conn);
        }
        return 0;
    }

}
